package com.saver.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


/**
 * Created by IntelliJ IDEA
 * Author: d-arlin@qq.com
 * Date: 2018/3/14
 * Time: 15:38
 */
public class SecurityUtils {

    /**
     * 编码格式
     */
    private static final String ENCODING = "UTF-8";
    /**
     * 加密算法
     */
    public static final String KEY_ALGORITHM = "AES";
    /**
     * 签名算法
     */
    public static final String SIGN_ALGORITHMS = "SHA1PRNG";

    /**
     * 加密
     *
     * @return
     */
    public static String encrypt(String content, String key) {
        if (content == null || key == null) return null;
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
            byte[] bytes;
            bytes = cipher.doFinal(content.getBytes("utf-8"));

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toHexString(bytes[i] & 0xFF);
                if (hex.length() == 1) hex = '0' + hex;
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }

    /**
     * 解密
     *
     * @return
     */
    public static String decrypt(String content, String key) {
        try {

            if (content == null || key == null) return null;

            if (content.length() < 1) return null;
            byte[] bytes = new byte[content.length() / 2];
            for (int i = 0; i < content.length() / 2; i++) {
                int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
                bytes[i] = (byte) (high * 16 + low);
            }

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));

            bytes = cipher.doFinal(bytes);
            return new String(bytes, "utf-8");
        } catch (Exception e) {
            System.out.println("error");
        }
        return null;
    }



}
